//
//  HHTimerButton.m
//  HHBroker
//
//  Created by He Wei on 9/18/15.
//  Copyright © 2015 harry. All rights reserved.
//

#import "HHTimerButton.h"

@implementation HHTimerButton
{
    NSTimer *_newTimer;

}

- (void)dealloc
{
    if (_newTimer) {
        if ([_newTimer isValid]) {
            [_newTimer invalidate];
        }
    }

}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setTitle:NSLocalizedString(@"重发验证码", nil) forState:UIControlStateNormal];
        [self setTitleColor:UIColorFromRGB(0x3b3b3b) forState:UIControlStateNormal];
        self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        self.titleLabel.font = kJiaYuanFontWithSize(15.0f);
        if (!_newTimer) {
            _newTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(startNewTimeOut) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:_newTimer forMode:NSRunLoopCommonModes];
            [_newTimer setFireDate:[NSDate distantFuture]];
        }
    }
    return self;
}

- (void)startNewTimeOut
{
    if (_timeOut <= 0) {
        self.userInteractionEnabled = YES;
        [self setTitle:NSLocalizedString(@"重发验证码", nil) forState:UIControlStateNormal];
    }
    else{
        self.userInteractionEnabled = NO;
        NSString *string = [NSString stringWithFormat:@"%ld%@",(long)_timeOut, NSLocalizedString(@"s后重新发送", nil)];
        [self setTitle:string forState:UIControlStateNormal];
        _timeOut--;
    }


}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setTitle:NSLocalizedString(@"重发验证码", nil) forState:UIControlStateNormal];
        [self setTitleColor:UIColorFromRGB(0x3b3b3b) forState:UIControlStateNormal];
        self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        self.titleLabel.font = kJiaYuanFontWithSize(15.0f);
        if (!_newTimer) {
            _newTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(startNewTimeOut) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:_newTimer forMode:NSRunLoopCommonModes];
            [_newTimer setFireDate:[NSDate distantFuture]];
        }
    }
    return self;
}
- (void)setTimeOut:(NSInteger)timeOut
{
    _timeOut = timeOut;
    if (_newTimer) {
        [_newTimer setFireDate:[NSDate distantPast]];
    }

}

- (void)startWithTimeOut:(NSInteger)aTimeOut
{
    dispatch_queue_t _queue;
    dispatch_source_t _timer;
    //设置倒计时时间
    __block NSInteger timeOut = aTimeOut;
    _queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _queue);
    
    //设置间隔多长时间执行 此处设置每秒执行
    
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0* NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (timeOut <= 0) {
            //倒计时结束 关闭线程 回到主线程
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
            //在主线程做点something
                self.enabled = YES;
                NSString *string = [NSString stringWithFormat:@"%@",NSLocalizedString(@"重发验证码", nil)];
                NSAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string];
                [self setAttributedTitle:attributeString forState:UIControlStateNormal];
                self.titleLabel.textAlignment = NSTextAlignmentCenter;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
            //回到主线程
                self.enabled = NO;
                NSString *string = [NSString stringWithFormat:@"(%ld)%@", (long)timeOut, NSLocalizedString(@"重发验证码", nil)];
                NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string];
                NSRange range = [string rangeOfString:string];
                NSDictionary *dic = @{NSForegroundColorAttributeName:[UIColor colorWithRed:155/255.0 green:155/255.0 blue:155/255.0 alpha:1], NSFontAttributeName:[UIFont systemFontOfSize:15.0f]};
                [attributeString setAttributes:attributeString range:range];
                [self setAttributedTitle:attributeString forState:UIControlStateNormal];
            });
            timeOut--;
        }
    });
    dispatch_resume(_timer);

}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
